import React,{ Component } from 'react'
import {
    Button,
    Row,
    Col,
    Input,
    InputNumber,
    Collapse,
    message,
    Menu,Dropdown,
} from 'antd';
import { LegionsProForm,LegionsProModal } from 'legions-pro-design';
import { bind,observer } from 'legions/store-react'
import ProjectStore from '../../stores/projectStore';
import { ProjectModules } from '../../interface/project';
import { InstanceProForm } from 'legions-pro-design/es/LegionsProForm/interface';
import { InstanceProModal } from 'legions-pro-design/es/LegionsProModal/interface';
import { InstanceProTable } from 'legions-pro-design/es/LegionsProTable/interface';
import { observable,action,computed } from 'mobx';
import { observableViewModel } from 'legions/store-utils'
import {
    PropertyTableOperationFormFields,
    PropertyTableOperationFormFieldsRule,
    PropertyKeyValueFormFields,
} from '../../models/form/propertyFormModel';
import { OperationEnum } from '../../constants/enum-data';
import { PropertyFormElementFormFieldsRule,PropertyFormElementFormFields,PropertyFormGroupGlobalFormFields } from '../../models/form/propertyFormElement';
import { title } from 'process';
import FormPropertyConfig from '../../components/property.config.form/formPropertyConfig';
import get from 'lodash/get'
import set from 'lodash/set'
import has from 'lodash/has'
import AddEvent from '../components.widget/addEvent';
import { fullProvider,lazyInject,inject } from 'legions-control-container';
import AddSelectOptions from '../components.widget/addSelectOptions';
import {IProFormFields} from 'legions-pro-design/es/LegionsStoreForm/interface'
import { FormCanvasDomain } from '../../services/components/formCanvasDomain';
import { HlLabeledValue } from 'legions-lunar/model';
import { getExecutableScript } from '../../utils/codemod';
import { tranformEvent } from '../../utils/form-page-codemod';
import { transformFuncToExeccodeast } from '../../utils/codemodCore';
import { toJS } from 'mobx';
interface IProps {
    store?: ProjectStore
}
const { Panel } = Collapse;
class ViewModel {
    @observable key: string = ''
}
@bind({ store: ProjectStore })
@observer
export default class FormProerty extends Component<IProps> {
    /** 分组信息编辑模态框实例 */
    modalRef: InstanceProModal = null
    viewModel = observableViewModel<ViewModel>(new ViewModel());
    /** 分组信息表单实例 */
    formGroupRef: InstanceProForm = null;
    @lazyInject(FormPropertyConfig)
    formPropertyConfig!: FormPropertyConfig;

    @lazyInject(FormCanvasDomain)
    formCanvasDomain!: FormCanvasDomain
    propertyElementConfig:  Array<IProFormFields['componentModel']> = [];
    constructor(props: IProps) {
        super(props)
        this.state = {
        }
        this.formPropertyConfig.registerInstance(this);
        this.propertyElementConfig = this.formPropertyConfig.createElementConfig();
    }

    addOptions() {
        this.modalRef.viewModel.visible = true;
        this.modalRef.viewModel.title = '添加数据项';
    }


    createElement() {
        return []
    }
    /** 获取表单属性 */
    get getFormComponentPropertyViewModel() {
        const formPropertyApp = this.props.store.context.formPropertyApp;
        const InputDataModel: PropertyFormElementFormFields = formPropertyApp.formProperyCommonRef.viewModel.InputDataModel as PropertyFormElementFormFields
        return InputDataModel
    }
    isEditGroupState() {
        const title = this.modalRef.viewModel.title as string;
        if (this.getFormComponentPropertyViewModel.groupList.value && title.indexOf('编辑') > -1) {
            return true;
        }
        return false;
    }
    clearGroupFormData() {
        this.formGroupRef.store.updateFormInputData(this.formGroupRef.uid,new PropertyFormGroupGlobalFormFields());
    }
    render() {
        const formPropertyApp = this.props.store.context.formPropertyApp;
        const projectCommonApp = this.props.store.context.projectCommonApp;
        return (
            <div>
                <Collapse defaultActiveKey={['1','0']}>
                    <Panel header="表单属性" key="0">
                        <LegionsProForm
                            <PropertyFormElementFormFields>
                            InputDataModel={PropertyFormElementFormFields}
                            mapPropsToFields={(props) => {
                                return new PropertyFormElementFormFields(props) // 实际处理结果实体
                            }}
                            onFieldsChange={(props,formFields: PropertyFormElementFormFields) => {
                                formPropertyApp.formProperyCommonRef.store.updateFormInputData(formPropertyApp.formProperyCommonRef.uid,formFields)
                                if (has(formFields,'layout')) {
                                    //@ts-ignore
                                    const value: (1|2|3|4) = parseInt(formFields.layout.value)
                                    formFields.layout && (formPropertyApp.propertyFormationVM.layout =  value);
                                }
                                formFields.sizes && (formPropertyApp.propertyFormationVM.size = formFields.sizes.value);
                            }}
                            onReady={(form,ref) => {
                                formPropertyApp.formProperyCommonRef = ref;
                            }}
                            colCount={1}
                            controls={this.formPropertyConfig.createConfig()}
                        ></LegionsProForm>
                    </Panel>
                    <Panel header="组件属性" key="1">
                        <LegionsProForm
                            <PropertyFormElementFormFields>
                            InputDataModel={PropertyFormElementFormFields}
                            mapPropsToFields={(props) => {
                                return new PropertyFormElementFormFields(props) // 实际处理结果实体
                            }}
                            onFieldsChange={(props,formFields: PropertyFormElementFormFields) => {
                                formPropertyApp.formProperyElementRef.store.updateFormInputData(formPropertyApp.formProperyElementRef.uid,formFields)
                                this.formCanvasDomain.asyncElementData(formFields)
                            }}
                            onReady={(form,ref) => {
                                formPropertyApp.formProperyElementRef = Object.assign(ref,{ that: this });
                            }}
                            colCount={1}
                            controls={ this.propertyElementConfig}
                        ></LegionsProForm>
                    </Panel>
                </Collapse>
                 {/*  ======= 表单项分组设置=====start */}
                <LegionsProModal
                        onOk={() => {
                            this.formGroupRef.viewModel.form.validateFields((err,values: PropertyFormGroupGlobalFormFields) => {
                                const value = PropertyFormGroupGlobalFormFields.formFieldsToData(PropertyFormGroupGlobalFormFields,this.formGroupRef.viewModel.InputDataModel)
                                if (!err) {
                                    formPropertyApp.propertyFormationVM.dispatchAction(() => {
                                        const InputDataModel: PropertyFormElementFormFields = formPropertyApp.formProperyCommonRef.viewModel.InputDataModel as PropertyFormElementFormFields
                                        const _index = formPropertyApp.propertyFormationVM.group.findIndex((item) => item.name === value['name'])
                                        if (_index < 0) {
                                            value['id'] = formPropertyApp.propertyFormationVM.group.length + 1;
                                            // @ts-ignore
                                            formPropertyApp.propertyFormationVM.group.push(value);

                                            if (this.isEditGroupState()) { // 编辑状态 如果id和name 都变了，则进行新增，删除源数据
                                                const _oldIndex = formPropertyApp.propertyFormationVM.group.findIndex((item) => item.id.toString() === InputDataModel.groupList.value.key)
                                                formPropertyApp.propertyFormationVM.group.splice(_oldIndex,1);
                                                message.success('更新成功');
                                            } else {
                                                message.success('添加成功');
                                            }
                                            formPropertyApp.propertyFormationVM.group = formPropertyApp.propertyFormationVM.group.slice()
                                            this.clearGroupFormData();
                                            formPropertyApp.formProperyCommonRef.methods.setFormStates<InstanceType<typeof LegionsProForm['LabelWithSelectModel']>>('groupList',(values) => {
                                                //@ts-ignore
                                                values.iFormProps.options = formPropertyApp.propertyFormationVM.group.map((item) => {
                                                    return {key:item.id,value:item.name}
                                                });
                                            })
                                            formPropertyApp.formProperyElementRef.methods.setFormStates<InstanceType<typeof LegionsProForm['LabelWithSelectModel']>>('subGroup',(values) => {
                                                //@ts-ignore
                                                values.iFormProps.options = formPropertyApp.propertyFormationVM.group.map((item) => {
                                                    return {key:item.id,value:item.name}
                                                });
                                            })
                                        } else {
                                            if (this.isEditGroupState()) { // 如果是编辑状态，且编辑后数据在源数据存在，则执行修改

                                                formPropertyApp.propertyFormationVM.group[_index] = {
                                                    ...formPropertyApp.propertyFormationVM.group[_index],
                                                    ... {
                                                        name: value['name'],
                                                        isFolding: value['isFolding'],
                                                        isSetFormSize: value['isSetFormSize'],
                                                    },
                                                }
                                                formPropertyApp.propertyFormationVM.group = formPropertyApp.propertyFormationVM.group.slice()
                                                message.success('数据更新成功');
                                                return;
                                            }
                                            message.warning('名称或标识重复添加,请重新填写')
                                        }
                                    })
                                }
                            })
                        }}
                        onReady={(value) => {
                            this.modalRef = value;
                            const width = 550;
                            this.modalRef.viewModel.width = width;
                        }}>
                            <React.Fragment>
                            <LegionsProForm
                                <PropertyFormGroupGlobalFormFields>
                                InputDataModel={PropertyFormGroupGlobalFormFields}
                                mapPropsToFields={(props) => {
                                    return new PropertyFormGroupGlobalFormFields(props) // 实际处理结果实体
                                }}
                                onFieldsChange={(props,formFields: PropertyFormGroupGlobalFormFields) => {
                                    this.formGroupRef.store.updateFormInputData(this.formGroupRef.uid,formFields)
                                }}
                                onReady={(form,ref) => {
                                    this.formGroupRef = ref;
                                }}
                                colCount={1}
                                controls={this.formPropertyConfig.createGroupConfig()}
                            ></LegionsProForm>
                        </React.Fragment>
                </LegionsProModal>
                {/*  ======= 表单项分组设置=====end */}
                <AddSelectOptions 
                    onOkSave={(selectValue) => {
                        const type = { '1': 'normal','2': 'expression','3': 'autoQuery' }
                        const componentType = formPropertyApp.propertyFormationVM.editComponentData.type;
                       
                        if (selectValue && selectValue.type === 'local') {
                            let property = '';
                            let parent = '';
                            if (componentType === 'select') {
                                property = 'selectOptions';
                                parent = 'selectOptionsValue';
                                //@ts-ignore
                                this.formCanvasDomain.asyncElementData({ selectValue: { value: selectValue.data } })
                            }
                            else if (componentType === 'radioButton') {
                                property = 'radioButtonOptions';
                                parent = 'radioButtonOptionsValue';
                                //@ts-ignore
                                this.formCanvasDomain.asyncElementData({ radioButtonValue: { value: selectValue.data } })
                            }
                            else if (componentType === 'radio') {
                                property = 'radioOptions';
                                parent = 'radioOptionsValue';
                                //@ts-ignore
                                this.formCanvasDomain.asyncElementData({ radioValue: { value: selectValue.data } })
                            }
                            const value = get(formPropertyApp.formProperyElementRef ? formPropertyApp.formProperyElementRef.viewModel.InputDataModel : {},`${parent}.value`) as HlLabeledValue
                            formPropertyApp.propertyFormationVM.updatePropertyValue({ value: value,property: parent,propertyType: type[selectValue.type] })
                            formPropertyApp.propertyFormationVM.updatePropertyValue({
                                value: toJS(selectValue.data),
                                property: property,
                                propertyType: 'normal',
                                parent: parent,
                            });
                        }
                        if (selectValue&&selectValue.type==='remote') {
                            const autoQuery = {};
                            
                            ['isRemote','isPageing','ApiUrl','token','method','params','transform','mappingEntity'].map((m) => {
                                let mappName = m;
                                if(m==='ApiUrl'){
                                    mappName='apiUrl'
                                }
                                const value = projectCommonApp.getAddSelectValueFormPropertyValue(mappName);
                                autoQuery[m] = value;
                            })
                            projectCommonApp.updateSelectValue('remote',{
                                //@ts-ignore
                                remote: autoQuery,
                            });
                            formPropertyApp.propertyFormationVM.updatePropertyValue({
                                value: autoQuery,
                                property: 'selectOptions',
                                propertyType: 'autoQuery',
                                parent: 'selectOptionsValue',
                            });
                            const receiveValue = 'this.props.store.context.formPropertyApp.propertyFormationVM.execcodeast';
                            const execcodeast = (name:string) => {
                                const code= transformFuncToExeccodeast(autoQuery[name],{
                                    propertyName: name,
                                    receiveValue: `${receiveValue}`,
                                });
                                eval(getExecutableScript(code,this));
                                return formPropertyApp.propertyFormationVM.execcodeast[name]
                            }
                            formPropertyApp.formPropertyDraggerRef.methods.setFormStates<InstanceType<typeof LegionsProForm['LabelWithSelectModel']>>(formPropertyApp.propertyFormationVM.editComponentData.keys,(value) => {
                                //@ts-ignore
                                value.iFormProps['autoQuery'] = {};
                                value.iFormProps['autoQuery'].ApiUrl = autoQuery['ApiUrl'];
                                value.iFormProps['autoQuery'].params = execcodeast('params');
                                value.iFormProps['autoQuery'].transform = execcodeast('transform');
                                value.iFormProps['autoQuery'].mappingEntity = execcodeast('mappingEntity');
                                value.iFormProps['autoQuery'].method = autoQuery['method'];
                                value.iFormProps['autoQuery'].token = execcodeast('token');
                                value.iFormProps.options = [];
                                if (has(autoQuery,'isRemote')) {
                                    value.iFormProps.remote = autoQuery['isRemote']
                                }
                                if (has(autoQuery,'isPageing')) {
                                    value.iFormProps.paging = autoQuery['isPageing']
                                }
                            })
                        }
                        
                  }}
                ></AddSelectOptions>
                <AddEvent
                    onOk={() => {
                        formPropertyApp.propertyFormationVM.dispatchAction(() => {
                            formPropertyApp.propertyFormationVM.execcodeast = null;
                            const eventName = formPropertyApp.propertyFormationVM.editComponentData.property;
                            eval(getExecutableScript(tranformEvent(
                                formPropertyApp.propertyFormationVM.codeValue,
                                eventName,
                                'this.props.store.context.formPropertyApp.propertyFormationVM.execcodeast'
                            ),this));
                            formPropertyApp.propertyFormationVM.updatePropertyValue({
                                value: formPropertyApp.propertyFormationVM.codeValue,
                                propertyType: 'function',
                                property: formPropertyApp.propertyFormationVM.editComponentData.property,
                                execast: formPropertyApp.propertyFormationVM.execcodeast,// 待转化 预览时用
                            });
                            const model: PropertyFormElementFormFields = formPropertyApp.formProperyElementRef.viewModel.InputDataModel as PropertyFormElementFormFields;
                            formPropertyApp.formPropertyDraggerRef.methods.setFormStates(formPropertyApp.propertyFormationVM.editComponentData.keys,(value) => {
                                if (model.eventList.value) {
                                    ['onChange','onFocus','onBlur'].map((item) => {
                                        if (item === model.eventList.value.label) {
                                            value.iFormProps[item] = formPropertyApp.propertyFormationVM.execcodeast[item];
                                        }
                                    })
                                }
                            })
                            formPropertyApp.propertyFormationVM.editComponentData.property = null;
                            projectCommonApp.formAddEventCodeExpressionModalRef.viewModel.visible = false;
                        })
                    }}
                    onEdit={(record) => {
                        formPropertyApp.propertyFormationVM.dispatchAction(() => {
                            let code = ''
                            const model = formPropertyApp.propertyFormationVM.getPropertyValue(record['event']);
                            if (model) {
                                code = model.value as string;
                            }
                            formPropertyApp.propertyFormationVM.codeValue = code;
                            projectCommonApp.formAddEventCodeExpressionModalRef.viewModel.visible = true;
                            projectCommonApp.formAddEventCodeExpressionModalRef.viewModel.title = `${record['event']}事件`;
                            formPropertyApp.propertyFormationVM.editComponentData.property = record['event'];
                        })
                    }}
                    onDelete={(record) => {
                        formPropertyApp.propertyFormationVM.deleteEvent(record['event'])
                        formPropertyApp.propertyFormationVM.updateEventData();
                    }}></AddEvent>
            </div>
        )
    }
}